package com.visionet.school.app.web.common.utils;


import com.visionet.school.app.web.common.utilities.props.PropsKeys;
import com.visionet.school.app.web.common.utilities.props.PropsUtil;
import com.visionet.school.app.web.common.utilities.string.StringBundler;
import com.visionet.school.app.web.entity.enums.FileEnums;
import com.visionet.school.app.web.entity.file.vo.FileVo;
import com.visionet.school.app.web.wechat.vo.MainVO;
import it.sauronsoftware.jave.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

/**
 * Created by hxpeng on 2017/3/29.
 */
public class DownLoadFileUtils {

    private static final Logger logger = LoggerFactory.getLogger(DownLoadFileUtils.class);

    //下载图片保存的地址
    private static final String SERVER_IMG_PATH = PropsUtil.getProperty(PropsKeys.SERVER_IMG_PATH);

    private static final String SERVER_PATH = PropsUtil.getProperty(PropsKeys.SERVER_PATH);

    private static final String SEPARATOR = "/";

    private static final int BUFFER_SIZE = 4096;

    /**
     * 远程文件路径下载
     * @param fileURL 微信文件路径
     * @param saveDir 保存地址
     * @throws IOException
     */
    public static String downloadFile(String fileURL, String saveDir) throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 检查http返回码
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String fileType = "";

            String contentType = httpConn.getHeaderField("Content-Type");
            //判断请求头中的contentType是否为文本类型
            if(StringUtils.isNotBlank(contentType) && contentType.equals("text/plain")){
                throw new NullPointerException("下载失败，未找到文件！");
            }
            //获取微信请求头，内包含文件名称
            String disposition = httpConn.getHeaderField("Content-Disposition");
            if (disposition != null) {
                // 从微信请求头获取文件名称
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10, disposition.length() - 1);
                }
            } else {
                // 从路径中获取文件名
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
            }
            fileType = fileName.substring(fileName.indexOf("."),fileName.length());

            //暂用时间撮命名图片文件
            fileName = String.valueOf(new Date().getTime()) + fileType;

            // 打开文件流
            InputStream inputStream = httpConn.getInputStream();

            String saveFilePath;
            if(StringUtils.isBlank(saveDir)){
                saveFilePath = SERVER_IMG_PATH + SEPARATOR + fileName;
            }else{
                saveFilePath = saveDir + SEPARATOR + fileName;
            }

            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            logger.info("文件：" + fileName + "下载完毕...........");
            saveFilePath = SERVER_PATH + SEPARATOR + fileName;
            return saveFilePath;
        } else {
            System.out.println("未找到下载文件. 服务器返回码: " + responseCode);
        }
        httpConn.disconnect();
        return null;
    }

    /**
     * 下载微信临时素材（动态图片/音频）
     * @param mediaId 微信文件路径
     * @param saveFilePath 保存路径
     * @param thumbnail 是否生成缩略图
     * @throws IOException
     */
    public static FileVo downloadWechatFile(String mediaId, String saveFilePath, Boolean thumbnail, String fileType) throws IOException {

        if(StringUtils.isBlank(saveFilePath) || StringUtils.isBlank(mediaId) || thumbnail == null || StringUtils.isBlank(fileType)){
            throw new RuntimeException("下载微信临时素材失败，缺少主要参数！");
        }

        HttpURLConnection conn = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        String fileName = "";
        String thumbnailImgPath = "";

        try {
            //获取文件保存的文件夹名称
            if(saveFilePath.charAt(saveFilePath.length()-1) == '/'){
                saveFilePath = saveFilePath.substring(0,saveFilePath.length()-1);
            }
            String folder = saveFilePath.substring(saveFilePath.lastIndexOf("/") + 1, saveFilePath.length());
            FileVo fileVo = new FileVo();

            String fileURL = MainVO.GetDownLoadMediaUrl(mediaId);

//            String fileURL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=EcwoaCxVAK_y9_AIpHE90b3oSWwcO7uMFoPa583-t50hkki1Or3V4jOff1FANKG_dyqGv1ZJnQLoUtk3VSnizme-eLJws_E03NpDVUkguo4k6JDHFXBXKDU-hubRbMkKNRAcAFAFJS" +
//                    "&media_id=hXmuuo7ADvhCPDE5WP5yR9Tf3WJ_fovYpzfPXYd6g5tgXpdWmCOqYERZtvixKA_a";
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            // 检查http返回码
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String contentType = httpConn.getHeaderField("Content-Type");
                //检查contentType
                if(StringUtils.isNotBlank(contentType) && contentType.equals("text/plain")){
                    throw new NullPointerException("获取微信mediaId：" + mediaId + "素材失败。");
                }
                //获取微信请求头，内包含文件名称
                String disposition = httpConn.getHeaderField("Content-Disposition");
                if (disposition != null) {
                    // 从微信请求头获取文件名称
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10, disposition.length() - 1);
                    }
                } else {
                    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
                }
                String[] fileNameArray = fileName.split("\\.");
                String fileNamePrefix = fileNameArray[0];//文件名
                String fileNamePostfix = fileNameArray[1];//文件后缀
                // 打开文件流
                inputStream = httpConn.getInputStream();
                //文件夹是否存在
                File file = new File(saveFilePath);
                if(!file.exists() && !file.isDirectory()){
                    file.mkdir();
                }
                String imgFileSavePath = saveFilePath + SEPARATOR + fileName;
                //写入文件
                fileOutputStream = new FileOutputStream(imgFileSavePath);
                int bytesRead = -1;
                byte[] buffer = new byte[BUFFER_SIZE];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
                if(fileNamePostfix.equals("amr")){
                    File source = new File(imgFileSavePath);
                    File target = new File(saveFilePath + SEPARATOR + fileNamePrefix + ".mp3");
                    logger.info("目标地址：" + target.getPath());
                    audioConvert(source,target);
                    fileName = fileNamePrefix + ".mp3";
                }
                //生成缩略图
                if(thumbnail){
                    String thumbnailImgName = fileNamePrefix + "_compress." + fileNamePostfix;
                    ThumbnailUtils.thumbnail(imgFileSavePath,saveFilePath + SEPARATOR + thumbnailImgName);
                    thumbnailImgPath = folder + SEPARATOR + thumbnailImgName;
                    fileVo.setThumbnail(SERVER_PATH + SEPARATOR + fileType + SEPARATOR + thumbnailImgPath);
                }
                logger.info("微信临时素材mediaId：" + mediaId + "下载完毕...........");

                fileVo.setMediaId(mediaId);
                StringBundler stringBundler = new StringBundler();
                stringBundler.append(SERVER_PATH).append(SEPARATOR)
                        .append(fileType).append(SEPARATOR)
                        .append(folder).append(SEPARATOR)
                        .append(fileName);
                fileVo.setFilePath(stringBundler.toString());
                fileVo.setFileName(fileName);
                fileVo.setStatus(FileEnums.SUCCESS.toKey());
                return fileVo;
            } else {
                logger.error("未找到下载文件. 服务器返回码: " + responseCode);
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("获取微信mediaId：" + mediaId + "素材失败,MSG:" + e.getMessage());
        }finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * amr转MP3
     * @param source
     * @param target
     */
    public static void audioConvert(File source, File target){
        AudioAttributes audio = new AudioAttributes();
        Encoder encoder = new Encoder();
        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String [] args) throws Exception{
//
//
////        String s = "hXmuuo7ADvhCPDE5WP5yR9Tf3WJ_fovYpzfPXYd6g5tgXpdWmCOqYERZtvixKA_a.jpg";
////        System.out.println(s.split("\\.")[0]);
//
//
//        FileVo fileVo =DownLoadFileUtils.downloadWechatFile("hXmuuo7ADvhCPDE5WP5yR9Tf3WJ_fovYpzfPXYd6g5tgXpdWmCOqYERZtvixKA_a"
//                ,"C:/Users/hxpeng./Desktop/dwdwsd",true);
//    }

}
